<script lang="ts" setup>
import { ref, defineProps, watch, onUnmounted, computed } from "vue";

import defaultAudio1 from '../../assets/audio/default1.wav';
import defaultAudio2 from '../../assets/audio/default2.wav';

const props = defineProps({
  color: String, // 默认颜色
  beat: String, // 节拍颜色
  start: Boolean, // 开始/停止高亮
  bpm: Number, // BPM (Beats Per Minute)
  beatCount: Number, // 每小节的节拍数
});

const beatsPerMeasure = computed(() => props.beatCount || 4);
const stopTime = computed(() => props.bpm ? (60 / props.bpm) * 1000 : 1000);
const defaultColor = props.color || "#eaeef1";
const firstHighlightColor = "#FFD700";
const otherHighlightColor = "#ADD8E6";

let timerId: number | null = null;
const transitionStyle = ref('transform 0.3s ease-in-out, background-color 0.3s ease-in-out, box-shadow 0.3s ease-in-out');
const cards = ref(
    Array.from({ length: beatsPerMeasure.value }, () => ({
      backgroundColor: defaultColor,
      scale: 1,
      boxShadow: "0 0 10px rgba(0,0,0,0.2)",
      animate: false,
    }))
);

const audio1 = new Audio(defaultAudio1);
const audio2 = new Audio(defaultAudio2);

function playAudioForCard(index: number) {
  if (index === 0) {
    audio1.play();
  } else {
    audio2.play();
  }
}

// // 根据beatCount计算每小节的节拍数
// const beatsPerMeasure = computed(() => {
//   return props.beatCount || 4; // 如果未定义，则默认使用4
// });
//
// // 根据BPM计算stopTime
// const stopTime = computed(() => {
//   if (!props.bpm) return 1000; // 默认值，以防bpm未定义
//   return (60 / props.bpm) * 1000;
// });
//
// // 默认颜色
// const defaultColor = props.color || "#eaeef1";
// const firstHighlightColor = "#FFD700"; // 第一个颜色框的高亮颜色
// const otherHighlightColor = "#ADD8E6"; // 其他颜色框的高亮颜色

// let timerId: number | null = null;

// const transitionStyle = ref('transform 0.3s ease-in-out, background-color 0.3s ease-in-out, box-shadow 0.3s ease-in-out');

// const cards = ref(
//   Array.from({ length: beatsPerMeasure.value }, () => ({
//     backgroundColor: defaultColor,
//     scale: 1, // 初始缩放比例
//     boxShadow: "0 0 10px rgba(0,0,0,0.2)", // 初始阴影
//     animate: false, // 控制是否应用动画
//   }))
// );

/**
 * 触发高亮效果
 */
function highlight(index: number, currentStopTime?: number) {
  const currentCard = cards.value[index];
  const highlightColor = index === 0 ? firstHighlightColor : otherHighlightColor;

  currentCard.backgroundColor = highlightColor;
  currentCard.scale = 1.2;
  currentCard.boxShadow = "0 0 20px rgba(0,0,0,0.5)";
  currentCard.animate = true;

  playAudioForCard(index);

  setTimeout(() => {
    if (props.start) {
      resetCard(currentCard);
      nextHighlight((index + 1) % beatsPerMeasure.value, currentStopTime);
    }
  }, currentStopTime || stopTime.value);
}
/**
 * 处理下一个卡片的高亮
 */
function nextHighlight(index: number, currentStopTime?: number) {
  clearTimeout(timerId as number); // 清除任何已存在的定时器
  timerId = setTimeout(() => {
    highlight(index, currentStopTime);
  }, 0) as any; // 立即执行下一次高亮
}

/**
 * 重置卡片状态
 */
function resetCard(card: any) {
  card.backgroundColor = defaultColor; // 恢复默认颜色
  card.scale = 1; // 恢复原始大小
  card.boxShadow = "0 0 10px rgba(0,0,0,0.2)"; // 恢复初始阴影
  card.animate = false; // 确保没有动画
}

watch(
  () => [props.start, props.beatCount, props.bpm],
  ([newStart, newBeatCount, newBPM]) => {
    // 清除所有定时器和重置卡片状态
    clearTimeout(timerId as number);
    timerId = null;
    cards.value.forEach(resetCard);
    let newBPMValue;
    if(newBPM==undefined || newBPM==null) {
      newBPMValue = 60;
    }else {
      newBPMValue = newBPM as any;
    }

    if (newStart) {
      // 根据新的bpm重新计算stopTime
      const currentStopTime = newBPMValue as any ? (60 / newBPMValue as any) * 1000 : 1000;

      // 更新颜色框数量
      cards.value = Array.from({ length: newBeatCount as any }, () => ({
        backgroundColor: defaultColor,
        scale: 1,
        boxShadow: "0 0 10px rgba(0,0,0,0.2)",
        animate: false,
      }));

      // 使用最新的stopTime开始高亮
      nextHighlight(0, currentStopTime);
    }
  },
  { immediate: true }
);

onUnmounted(() => {
  clearTimeout(timerId as number);
});
</script>

<template>
  <div id="card-light">
    <t-grid :column="beatsPerMeasure" class="card-grid">
      <div
        v-for="(card, index) in cards"
        :key="index"
        style="width: 100%;height: 100%;display: flex;"
      >
        <div
          class="card-one"
          :style="{
            backgroundColor: card.backgroundColor,
            transform: `scale(${card.scale})`,
            boxShadow: card.boxShadow,
            transition: card.animate ? transitionStyle : ''
          }"
        ></div>
      </div>
    </t-grid>
  </div>
</template>

<style lang="less" scoped>
.card-grid {
  overflow: visible;
  display: flex;
}
.card-one {
  margin: auto;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
</style>